package com.example.synchost5.controller;

import com.example.synchost5.service.SyncHostService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

@RestController
@RequestMapping("/")
public class SyncHostController {

    private static final Logger logger = LoggerFactory.getLogger(SyncHostController.class);

    private final SyncHostService syncHostService;

    public SyncHostController(SyncHostService syncHostService) {
        this.syncHostService = syncHostService;
    }

    /**
     * 注册
     * @param configName 配置名, 全局唯一
     * @param staticPart 静态部分
     * @param dynamicPart 想每次更新的部分
     * @return true or false
     */
    @PostMapping("/host/{configName}")
    public Object save(@PathVariable String configName,
                       @RequestParam String staticPart,
                       @RequestParam String dynamicPart) {
        logger.info("Save config for " + configName);
        return syncHostService.saveConfig(configName, staticPart, dynamicPart);
    }

    /**
     * 获取 host 文件
     * @param configName 配置名称
     * @param response 用于返回下载流的 response
     * @return ok
     */
    @GetMapping("/host/{configName}")
    public Object getHost(@PathVariable String configName, HttpServletResponse response) {
        String result = syncHostService.getFullHostFile(configName);
        if (result == null) {
            logger.info("Result for " + configName + " is null, return null");
            return "null";
        }
        response.setHeader("content-type", "application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=hosts");
        response.setContentType("application/octet-stream");
        try (OutputStream os = response.getOutputStream()) {
            os.write(result.getBytes(StandardCharsets.UTF_8));
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        logger.info("Return result for " + configName);
        return "ok";
    }

    @PostMapping("/fetch/20220321")
    public void autoFetch() {
        syncHostService.fetch();
    }

}
